package com.cloud.lan.pub.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;


/**
 * JSON基础转换
 * @author ErKang
 * @date Created in 2018/2/16 16:18
 * @title Json.java
 * Department: Product development
 */
public class Json {

    private static ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();

    public static <T> T toObject(String json, Class<T> c) {
        try {
            return mapper.readValue(json, c);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toObject(String json, TypeReference<?> valueTypeRef) {
        try {
            return (T) mapper.readValue(json, valueTypeRef);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toString(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static JsonNode toJsonNode(String json) {
        try {
            return mapper.readTree(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
